/*******************************************************************************
 * Package: com.song.flowable.service.impl
 * Type:    BpmProcessDefinitionServiceImpl
 * Date:    2023-11-27 22:24
 *
 * Copyright (c) 2023 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.flowable.service.impl;

import cn.hutool.core.util.StrUtil;
import com.song.flowable.convert.ProcessDefinitionConvert;
import com.song.flowable.dto.ProcessDefinitionPageDTO;
import com.song.flowable.service.BpmProcessDefinitionService;
import com.song.flowable.vo.ProcessDefinitionVO;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 功能描述：
 *
 * @author Songxianyang
 * @date 2023-11-27 22:24
 */
@Service
public class BpmProcessDefinitionServiceImpl implements BpmProcessDefinitionService {

    @Resource
    private RepositoryService repositoryService;
    /**
     * 获得流程定义分页
     *
     * @param dto 分页入参
     * @return List<ProcessDefinition>
     */
    @Override
    public List<ProcessDefinitionVO> getProcessDefinitionPage(ProcessDefinitionPageDTO dto) {
        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery();
        if (StringUtils.isNotBlank(dto.getKey())) {
            definitionQuery.processDefinitionKey(dto.getKey());
        }
        // 执行查询
        List<ProcessDefinition> processDefinitions = definitionQuery.orderByProcessDefinitionVersion().desc()
                .listPage(dto.getPage(), dto.getPageSize());
        List<ProcessDefinitionVO> processDefinitionVOS = ProcessDefinitionConvert.INSTANCE.toConvertProcessDefinitionList(processDefinitions);
        return processDefinitionVOS;
    }
    /**
     * 获得流程定义对应的 BPMN XML
     *
     * @param id 流程定义编号
     * @return BPMN XML
     */
    @Override
    public String getXML(String id) {
        BpmnModel bpmnModel = repositoryService.getBpmnModel(id);
        if (bpmnModel == null) {
            return null;
        }
        BpmnXMLConverter converter = new BpmnXMLConverter();
        return StrUtil.utf8Str(converter.convertToXML(bpmnModel));
    }
}
